<?php
namespace App\Logics;
// +----------------------------------------------------------------------
// | Copyright (c) 2024~至今 迪钰国际旅行社 版权所有.
// +----------------------------------------------------------------------
// | Author: dxf &lt;xiangfei2007@126.com&gt;
// +----------------------------------------------------------------------
// | Date: 2024/8/19 13:09
// +----------------------------------------------------------------------

use App\Exceptions\InternalException;
use App\Models\User;
use App\Services\TokenService;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Redis;

class AuthLogic extends BaseLogic
{
    /**
     *  管理员登录函数
     *  根据不同的登录类型（账号、手机、微信），验证用户身份并生成新的登录令牌
     *
     * @param array $params 包含登录类型和相应凭证的参数数组
     * @param string $old_token 用户的旧登录令牌，用于更新登录状态
     * @return bool|mixed|string 新生成的登录令牌
     * @throws InternalException
     * @throws \App\Exceptions\TokenInvalidException
     * Date:    2024/8/20 15:04
     */
    public function adminLogin($params,$old_token): mixed
    {
        $query = User::query();
        if($params['login_type'] == 'account'){
            $check  = $query->select('id','account','phone','password','status')->where('account', $params['account'])->first();
            if(!$check){
                throw new InternalException('账号不存在');
            }
            if (!Hash::check($params['password'], $check->password)) {
                throw new InternalException('请输入正确密码');
            }
        }elseif($params['login_type'] == 'phone'){
            $check  = $query->select('id','account','phone','status')->where('phone', $params['phone'])->first();
        }else{
            $check  = $query->select('id','account','phone','status')->where('wechat_unionid', $params['wechat_unionid'])->first();
        }

        if (!$check || $check->status != 1) {
            throw new InternalException('账号不存在或者被禁用了');
        }

        $tokenService = new TokenService();
        $expire_time  = config('custom.app_expire_time', 604800);
        return ['token'=>$tokenService->saveTokenToLoginPool($check,$expire_time,$old_token),'current_user'=>$check];
    }

    /**
     * 后台用户登出
     * @param string $token
     * @return true
     * @throws InternalException
     * Date:    2024/8/20 15:09
     */
    public function adminLogout(string $token): bool
    {
        $check_arr = explode('.', base64_decode($token, true));
        if (count($check_arr) != 3) {
            throw new InternalException('token格式错误');
        }
        $tokenService = new TokenService();
        $check_hs256 = $tokenService->hmacSha256($check_arr[2]);
        Redis::del($check_hs256);
        return true;
    }


}
